package com.weitu.contractor.controller;

import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.*;
import com.weitu.contractor.service.*;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.definition.constant.FlowDefConstants;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.fireflow.kernel.KernelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/18
 */
@Controller
@RequestMapping(value = "contractor/contractorAudit")
public class ContractorAuditController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/contractorAudit";
    private final ContractorAuditService contractorAuditService;
    private final ManagerCertService managerCertService;
    private final ContractorAuditHistoryService contractorAuditHistoryService;
    private final SafeProductCertService safeProductCertService;
    private final SafeProductCertHistoryService safeProductCertHistoryService;
    private final ManagerCertHistoryService managerCertHistoryService;
    private final ContractorInfoService contractorInfoService;
    private final ContractorStaffService contractorStaffService;
    private final FlowManagementService flowManagementService;
    private final DataAuthorityService dataAuthorityService;

    @Autowired
    public ContractorAuditController(ContractorAuditService contractorAuditService
            , ManagerCertService managerCertService
            , ContractorAuditHistoryService contractorAuditHistoryService
            , SafeProductCertService safeProductCertService
            , SafeProductCertHistoryService safeProductCertHistoryService
            , ManagerCertHistoryService managerCertHistoryService
            , ContractorInfoService contractorInfoService
            , ContractorStaffService contractorStaffService
            , FlowManagementService flowManagementService
            , DataAuthorityService dataAuthorityService) {
        this.contractorAuditService = contractorAuditService;
        this.managerCertService = managerCertService;
        this.contractorAuditHistoryService = contractorAuditHistoryService;
        this.safeProductCertService = safeProductCertService;
        this.safeProductCertHistoryService = safeProductCertHistoryService;
        this.managerCertHistoryService = managerCertHistoryService;
        this.contractorInfoService = contractorInfoService;
        this.contractorStaffService = contractorStaffService;
        this.flowManagementService = flowManagementService;
        this.dataAuthorityService = dataAuthorityService;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        ContractorAuditCriteria example = new ContractorAuditCriteria();
        ContractorAuditCriteria.Criteria criteria = example.createCriteria().andDelStateEqualTo(0);
        putSearchCriteria(criteria);

        int count = contractorAuditService.countByCriteria(example);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            example.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        example.setPageView(pageView);

        List<ContractorAudit> contractorAudits = contractorAuditService.selectByCriteria(example);

        return dataGridPagination.flushDataGridData(contractorAudits);
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return MODULE_BATH_PATH + "/add";
    }

    @SystemLog(module = "承包商资质审查", methods = "添加承包商资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(ContractorAudit contractorAudit) throws Exception {
        if (contractorAuditService.checkIfExist(contractorAudit.getContractorId(),
                contractorAudit.getContractorTypeId())) {
            return fail("该承包商已有同类型数据，请重新选择类型！");
        }
        contractorAudit.setId(IDGenerator.getId());
        contractorAudit.setAddUserId(getSessionUser().getId());
        contractorAudit.setAddDeptId(getSessionUser().getDepartment().getId());
        contractorAudit.setAddTime(DateTimeUtil.formatterDateTime());
        if (contractorAuditService.insertSelective(contractorAudit) > 0) {
            return success("保存成功！", contractorAudit);
        } else {
            return fail("保存失败！");
        }
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id, String businessId, String workItemId) throws Exception {
        if (StringUtils.isNotEmpty(businessId)) {
            id = businessId;
            WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
            model.addAttribute("workflowReview", workflowReview);
        }
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/delay", method = RequestMethod.GET)
    public String delay(Model model, String id) {
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/renew", method = RequestMethod.GET)
    public String renew(Model model, String id) {
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Model model, String id) {
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @RequestMapping(value = "/copy", method = RequestMethod.GET)
    public String copy(Model model, String id) {
        putAttributesIntoModel(model, id);
        return MODULE_BATH_PATH + "/edit";
    }

    @SystemLog(module = "承包商资质审查", methods = "更新承包商资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(ContractorAudit contractorAudit) throws Exception {
        if (contractorAuditService.checkIfExist(contractorAudit.getContractorId(),
                contractorAudit.getContractorTypeId(),
                contractorAudit.getId())) {
            return fail("该承包商已有同类型数据，请重新选择类型！");
        }
        contractorAudit.setUpdateUserId(getSessionUser().getId());
        contractorAudit.setUpdateDeptId(getSessionUser().getDepartment().getId());
        contractorAudit.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (contractorAuditService.updateByPrimaryKeySelective(contractorAudit) > 0) {
            return success("保存成功！", contractorAudit);
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "承包商资质审查", methods = "提交承包商资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public AjaxResult submitAjax(ContractorAudit contractorAudit, String nextUserId) throws Exception {
        if (contractorAuditService.checkIfExist(contractorAudit.getContractorId(),
                contractorAudit.getContractorTypeId(),
                contractorAudit.getId())) {
            return fail("该承包商已有同类型数据，请重新选择类型！");
        }
        contractorAudit.setUpdateUserId(getSessionUser().getId());
        contractorAudit.setUpdateDeptId(getSessionUser().getDepartment().getId());
        contractorAudit.setUpdateTime(DateTimeUtil.formatterDateTime());
        contractorAudit.setAuditState(1);
        if (contractorAuditService.updateByPrimaryKeySelective(contractorAudit) > 0) {
            handleFlowStart(contractorAudit, nextUserId);
            return success("提交成功！", contractorAudit);
        }
        return fail("提交失败！");
    }

    @SystemLog(module = "承包商资质审查", methods = "审核承包商资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/audit", method = RequestMethod.POST)
    public AjaxResult auditAjax(HttpServletRequest request) throws Exception {
        if (handleFlowEnd(request)) {
            return success("审批成功！");
        }
        return fail("审批失败！");
    }

    @SystemLog(module = "承包商资质审查", methods = "删除承包商资质审查信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (contractorAuditService.deleteByPrimaryKey(id) > 0) {
            return success("删除承包商资质审查信息成功！");
        } else {
            return fail("删除承包商资质审查信息失败！");
        }
    }

    @SystemLog(module = "承包商资质审查", methods = "安全生产许可证资质延期")
    @ResponseBody
    @RequestMapping(value = "/delay", method = RequestMethod.POST)
    @Transactional
    public AjaxResult delayAjax() throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        putParametersIntoMap(paramMap);
        String safeCertId = (String) paramMap.get("safeCertId");
        String responsibleCertId = (String) paramMap.get("responsibleCertId");
        String supervisorCertId = (String) paramMap.get("supervisorCertId");
        String safeDutierCertId = (String) paramMap.get("safeDutierCertId");
        String validEndDate = (String) paramMap.get("validEndDate");
        String validEndDate_responsible = (String) paramMap.get("validEndDate_responsible");
        String validEndDate_supervisor = (String) paramMap.get("validEndDate_supervisor");
        String validEndDate_safeDutier = (String) paramMap.get("validEndDate_safeDutier");

        if (StringUtils.isNotEmpty(safeCertId)) {
            if (!updateSafeProductCertValidEndDate(safeCertId, validEndDate)) {
                return fail("延期失败！");
            }
        }

        if (StringUtils.isNotEmpty(responsibleCertId)) {
            if (!updateManagerCertValidEndDate(responsibleCertId, validEndDate_responsible)) {
                return fail("延期失败");
            }
        }
        if (StringUtils.isNotEmpty(supervisorCertId) && !StringUtils.equals(responsibleCertId, supervisorCertId)) {
            if (!updateManagerCertValidEndDate(supervisorCertId, validEndDate_supervisor)) {
                return fail("延期失败");
            }
        }
        if (StringUtils.isNotEmpty(safeDutierCertId) && !StringUtils.equals(responsibleCertId, safeDutierCertId) && !StringUtils.equals(supervisorCertId, safeDutierCertId)) {
            if (!updateManagerCertValidEndDate(safeDutierCertId, validEndDate_safeDutier)) {
                return fail("延期失败");
            }
        }
        return success("延期成功！");
    }

    @SystemLog(module = "承包商资质审查", methods = "续用承包商")
    @ResponseBody
    @RequestMapping(value = "/renew", method = RequestMethod.POST)
    public AjaxResult renewAjax(ContractorAudit contractorAudit) throws Exception {
        if (contractorAuditService.checkIfExist(contractorAudit.getContractorId(),
                contractorAudit.getContractorTypeId(),
                contractorAudit.getId())) {
            return fail("该承包商已有同类型数据，请重新选择类型！");
        }
        contractorAudit.setAddTime(getSessionUser().getId());
        contractorAudit.setAddDeptId(getSessionUser().getDepartment().getId());
        contractorAudit.setAddTime(DateTimeUtil.formatterDateTime());
        //TODO:确认续用时需要更新资质审查历史数据的时间
        if (contractorAuditService.updateByPrimaryKeySelective(contractorAudit) > 0) {
            return success("提交成功！", contractorAudit);
        }
        return fail("提交失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/historyList", method = RequestMethod.POST)
    public Object auditHistoryListAjax(HttpServletRequest request, String contractorId, String contractorTypeId) throws Exception {
        ContractorAuditHistoryCriteria criteria = new ContractorAuditHistoryCriteria();
        criteria.createCriteria()
                .andDelStateEqualTo(0)
                .andContractorIdEqualTo(contractorId)
                .andContractorTypeIdEqualTo(contractorTypeId);

        int count = contractorAuditHistoryService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        criteria.setPageView(pageView);

        List<ContractorAuditHistory> contractorAuditHistories = contractorAuditHistoryService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(contractorAuditHistories);
    }

    @RequestMapping(value = "/auditedList", method = RequestMethod.GET)
    public String auditedList() {
        return MODULE_BATH_PATH + "/auditedList";
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(ContractorAuditCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("contractorName"))) {
            List<String> contractorIds = contractorInfoService.selectContractorIdsByName(getPara("contractorName"));
            if (contractorIds.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andContractorIdIn(contractorIds);
            }
        }
        if (StringUtils.isNotEmpty(getPara("contractorTypeId"))) {
            criteria.andContractorTypeIdEqualTo(getPara("contractorTypeId"));
        }
        if (StringUtils.isNotEmpty(getPara("validEndDateMin"))) {
            List<String> contractorIds = safeProductCertService.selectContractorIdsByValidEndDateGreaterThanOrEqualTo(getPara("validEndDateMin"));
            if (contractorIds.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andContractorIdIn(contractorIds);
            }
        }
        if (StringUtils.isNotEmpty(getPara("validEndDateMax"))) {
            List<String> contractorIds = safeProductCertService.selectContractorIdsByValidEndDateLessThanOrEqualTo(getPara("validEndDateMax"));
            if (contractorIds.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andContractorIdIn(contractorIds);
            }
        }
        if (StringUtils.isNotEmpty(getPara("responsibleName"))) {
            List<String> ids = contractorStaffService.selectIdsByName(getPara("responsibleName"));
            if (ids.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andResponsibleIdIn(ids);
            }
        }
        if (StringUtils.isNotEmpty(getPara("supervisorName"))) {
            List<String> ids = contractorStaffService.selectIdsByName(getPara("supervisorName"));
            if (ids.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andSupervisorIdIn(ids);
            }
        }
        if (StringUtils.isNotEmpty(getPara("safeDutierName"))) {
            List<String> ids = contractorStaffService.selectIdsByName(getPara("safeDutierName"));
            if (ids.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andSafeDutierIdIn(ids);
            }
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        if (StringUtils.isNotEmpty(getPara("auditState"))) {
            criteria.andAuditStateEqualTo(getParaToInt("auditState"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }

    /**
     * 获取前台页面可用的对象实体
     *
     * @param list 列表
     * @return 对象实体
     */
    private ManagerCert getValidManagerCert(List<ManagerCert> list) {
        if (list.size() == 1) {
            return list.get(0);
        } else {
            return new ManagerCert();
        }
    }

    /**
     * 添加安全许可证历史信息
     *
     * @param safeProductCert 证书对象实体
     * @return 是否成功
     */
    private boolean addSafeProductCertHistory(SafeProductCert safeProductCert) {
        SafeProductCertHistory history = new SafeProductCertHistory();
        history.setId(IDGenerator.getId());
        history.setAddUserId(getSessionUser().getId());
        history.setAddDeptId(getSessionUser().getDepartment().getId());
        history.setAddTime(DateTimeUtil.formatterDateTime());
        history.setCertId(safeProductCert.getId());
        history.setContractorId(safeProductCert.getContractorId());
        history.setName(safeProductCert.getName());
        history.setCertCode(safeProductCert.getCertCode());
        history.setValidStartDate(safeProductCert.getValidStartDate());
        history.setValidEndDate(safeProductCert.getValidEndDate());
        return safeProductCertHistoryService.insertSelective(history) > 0;
    }

    /**
     * 添加安全管理人员资格证历史信息
     *
     * @param managerCert 证书对象
     * @return 是否成功
     */
    private boolean addManagerCertHistory(ManagerCert managerCert) {
        ManagerCertHistory history = new ManagerCertHistory();
        history.setId(IDGenerator.getId());
        history.setAddUserId(getSessionUser().getId());
        history.setAddDeptId(getSessionUser().getDepartment().getId());
        history.setAddTime(DateTimeUtil.formatterDateTime());
        history.setCertId(managerCert.getId());
        history.setPersonId(managerCert.getPersonId());
        history.setName(managerCert.getName());
        history.setCertCode(managerCert.getCertCode());
        history.setValidStartDate(managerCert.getValidStartDate());
        history.setValidEndDate(managerCert.getValidEndDate());
        return managerCertHistoryService.insertSelective(history) > 0;
    }

    /**
     * 添加资质审查历史历史信息
     *
     * @param contractorAudit 资质审查数据
     * @return 是否成功
     */
    private boolean addContractorAuditHistory(ContractorAudit contractorAudit) {
        ContractorAuditHistory history = new ContractorAuditHistory();
        history.setId(IDGenerator.getId());
        history.setAddUserId(getSessionUser().getId());
        history.setAddDeptId(getSessionUser().getDepartment().getId());
        history.setAddTime(DateTimeUtil.formatterDateTime());
        history.setContractorId(contractorAudit.getContractorId());
        history.setContractorTypeId(contractorAudit.getContractorTypeId());
        history.setYear(contractorAudit.getYear());
        history.setContractorIntellStartDate(contractorAudit.getContractorIntellStartDate());
        history.setContractorIntellEndDate(contractorAudit.getContractorIntellEndDate());
        history.setResponsibleId(contractorAudit.getResponsibleId());
        history.setSupervisorId(contractorAudit.getSupervisorId());
        history.setSafeDutierId(contractorAudit.getSafeDutierId());
        history.setIsEpc(contractorAudit.getIsEpc());
        history.setIsHseSystem(contractorAudit.getIsHseSystem());
        history.setAuditState(contractorAudit.getAuditState());
        history.setIsQualified(contractorAudit.getIsQualified());
        return contractorAuditHistoryService.insertSelective(history) > 0;
    }

    /**
     * 放入edit页面所需的页面属性
     *
     * @param model 页面对象
     * @param id    资质审查id
     */
    private void putAttributesIntoModel(Model model, String id) {
        ContractorAudit contractorAudit = contractorAuditService.selectByPrimaryKey(id);
        List<ManagerCert> managerCertResponsibleList = managerCertService.selectByPersonId(contractorAudit.getResponsibleId());
        List<ManagerCert> managerCertSupervisorList = managerCertService.selectByPersonId(contractorAudit.getSupervisorId());
        List<ManagerCert> managerCertSafeDutierList = managerCertService.selectByPersonId(contractorAudit.getSafeDutierId());
        ManagerCert managerCertResponsible = getValidManagerCert(managerCertResponsibleList);
        ManagerCert managerCertSupervisor = getValidManagerCert(managerCertSupervisorList);
        ManagerCert managerCertSafeDutier = getValidManagerCert(managerCertSafeDutierList);
        try {
            checkValidEndDate(model, contractorAudit.getSafeProductCert().getValidEndDate(), "safeCert");
            checkValidEndDate(model, managerCertResponsible.getValidEndDate(), "managerCertResponsible");
            checkValidEndDate(model, managerCertSupervisor.getValidEndDate(), "managerCertSupervisor");
            checkValidEndDate(model, managerCertSafeDutier.getValidEndDate(), "managerCertSafeDutier");
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("contractorAudit", contractorAudit);
        model.addAttribute("managerCertResponsible", managerCertResponsible);
        model.addAttribute("managerCertSupervisor", managerCertSupervisor);
        model.addAttribute("managerCertSafeDutier", managerCertSafeDutier);
    }

    /**
     * 根据超期情况对结束日期进行不同状态的预警
     *
     * @param model   页面属性
     * @param endDate 结束日期
     * @param type    类型
     * @throws ParseException 解析异常
     */
    private void checkValidEndDate(Model model, String endDate, String type) throws ParseException {
        if (endDate != null) {
            Date date = DateUtils.parseDate(endDate, new String[]{"yyyy-MM-dd"});
            Date oneMonthAgo = DateUtils.addDays(date, -30);
            Date now = new Date();
            if (date.before(now)) {
                model.addAttribute(type + "_validEndDate_state", "important");
            } else if (oneMonthAgo.before(now)) {
                model.addAttribute(type + "_validEndDate_state", "warning");
            }
        } else {
            model.addAttribute(type + "_validEndDate_state", "");
        }
    }

    /**
     * 对安全生产许可证进行延期和插入历史数据
     *
     * @param certId       证书id
     * @param validEndDate 结束日期
     * @return 是否成功
     */
    private boolean updateSafeProductCertValidEndDate(String certId, String validEndDate) throws Exception {
        SafeProductCert safeProductCert = safeProductCertService.selectByPrimaryKey(certId);
        if (validEndDate.equals(safeProductCert.getValidEndDate())) {
            return true;
        }
        safeProductCert.setUpdateUserId(getSessionUser().getId());
        safeProductCert.setUpdateDeptId(getSessionUser().getDepartment().getId());
        safeProductCert.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (addSafeProductCertHistory(safeProductCert)) {
            safeProductCert.setValidEndDate(validEndDate);
            return safeProductCertService.updateByPrimaryKeySelective(safeProductCert) > 0;
        }
        return false;
    }

    /**
     * 对安全管理人员资格证进行延期和插入历史数据
     *
     * @param certId       证书id
     * @param validEndDate 结束日期
     * @return 是否成功
     */
    private boolean updateManagerCertValidEndDate(String certId, String validEndDate) throws Exception {
        ManagerCert managerCert = managerCertService.selectByPrimaryKey(certId);
        if (validEndDate.equals(managerCert.getValidEndDate())) {
            return true;
        }
        managerCert.setUpdateUserId(getSessionUser().getId());
        managerCert.setUpdateDeptId(getSessionUser().getDepartment().getId());
        managerCert.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (addManagerCertHistory(managerCert)) {
            managerCert.setValidEndDate(validEndDate);
            return managerCertService.updateByPrimaryKeySelective(managerCert) > 0;
        }
        return false;
    }

    /**
     * 处理工作流开始
     *
     * @param contractorAudit 参数实体
     * @param nextUserId      下个处理人id
     * @throws Exception 异常
     */
    private void handleFlowStart(ContractorAudit contractorAudit, String nextUserId) throws Exception {
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put(FlowDefConstants.FLOW_FIRSTUSER_ID, nextUserId);
        String content = "承包商资质审查流程";
        //启动流程实例
        flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_CONTRACTOR_AUDIT
                , contractorAudit.getId()
                , content
                , getSessionUser().getName()
                , dataMap);
    }

    /**
     * 处理工作流
     *
     * @param request 请求
     * @throws KernelException 内核异常
     */
    private boolean handleFlowEnd(HttpServletRequest request) throws KernelException {
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = flowManagementService.saveWorkflowReview(workflowReview);

        //结束环节，继续流程向下执行
        if (boo) {
            flowManagementService.workItemComplete(workItemId);
            int auditState = Integer.parseInt(request.getParameter("auditState").trim());
            ContractorAudit contractorAudit = new ContractorAudit();
            contractorAudit.setId(request.getParameter("businessId"));
            contractorAudit.setAuditState(auditState);
            contractorAuditService.updateByPrimaryKeySelective(contractorAudit);
            return true;
        }
        return false;
    }
}
